package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public void createHtmlToMinIO(Long articleId) {
        try {
            //已知，文章的id  1302865306489733122
            //1.根据文章id查询文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, articleId));
            if(null != apArticleContent && StringUtils.isNotBlank(apArticleContent.getContent())){
                //2.根据文章内容结合freemarker生成静态的html文件
                Template template = configuration.getTemplate("article.ftl");
                Map<String,Object> dataMap = new HashMap<>();
                dataMap.put("content", JSONArray.parseArray(apArticleContent.getContent()));

                StringWriter out = new StringWriter();
                template.process(dataMap,out);

                //流转换
                InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());

                //3.把生成好的文件上传到minio,得到一个访问的路径
                String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);

                //4.把访问路径存入文章表的static_url字段中
                ApArticle apArticle = new ApArticle();
                apArticle.setId(apArticleContent.getArticleId());
                apArticle.setStaticUrl(path);
                apArticleMapper.updateById(apArticle);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
